package com.boang.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.swing.plaf.PanelUI;
import java.util.Properties;

/*
  @author: 13813
  @date: 2024/7/25 9:14
*/
//@PropertySource("classpath:db.properties")
public class MybatisConfig {

//    @Value("${mysql.url}")
//    private String url;
//    @Value("${mysql.username}")
//    private String userName;
//    @Value("${mysql.password}")
//    private String password;

    //把方法的返回值对象交给spring容器管理
    @Bean(name = "dataSource")
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost/48db");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        //最大连接数
        dataSource.setMaxActive(5);
        //最小连接数
        dataSource.setMinIdle(3);
        //初始化连接数
        dataSource.setInitialSize(2);
        return dataSource;
    }

    @Bean(name = "sqlSessionFactoryBean")
    public SqlSessionFactoryBean sqlSessionFactoryBean(DruidDataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        //批量设置实体类别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.boang.po");
        return sqlSessionFactoryBean;
    }

    //
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.boang.dao");
        return mapperScannerConfigurer;
    }

    //事务管理器
    @Bean
    public DataSourceTransactionManager transactionManager(DruidDataSource dataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}
